﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.Loader;
using Autofac;
using Autofac.Extensions.DependencyInjection;
using Autofac.Extras.Quartz;
using Hhmocon.Mes.Cache;
using Hhmocon.Mes.Util.AutofacManager;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyModel;
using IContainer = Autofac.IContainer;
using Hhmocon.Mes.Repository;
using Hhmocon.Mes.Repository.Repository;
using Hhmocon.Mes.Util.String;

namespace Hhmocon.Mes.Application
{
    public static class AutofacExt
    {
        private static IContainer _container;
       
        /// <summary>
        /// 使用容器的三部曲:实例化一个容器、注册、获取服务
        /// </summary>
        /// <param name="builder"></param>
        public static void InitAutofac(ContainerBuilder builder)
        {

            //注册数据库基础操作和工作单元
            builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly());
            builder.RegisterType(typeof(CacheContext)).As(typeof(ICacheContext));
            builder.RegisterType(typeof(HttpContextAccessor)).As(typeof(IHttpContextAccessor));

            //注入授权
            //builder.RegisterType(typeof(UserAuthApp)).As(typeof(IUserAuth));


            //业务注入
            builder.RegisterType(typeof(BaseCustomerRepository)).As(typeof(IBaseCustomerRepository));
            
            builder.RegisterType<PikachuRepository>();
            builder.RegisterType<SqlAssemble>();

            InitDependency(builder);

            builder.RegisterModule(new QuartzAutofacFactoryModule());
        }



        /// <summary>
        /// 注入所有继承了IDependency接口
        /// </summary>
        /// <param name="builder"></param>
        private static void InitDependency(ContainerBuilder builder)
        {
            Type baseType = typeof(IDependency);
            var compilationLibrary = DependencyContext.Default
                .CompileLibraries
                .Where(x => !x.Serviceable
                            && x.Type == "project")
                .ToList();
            var count1 = compilationLibrary.Count;
            List<Assembly> assemblyList = new List<Assembly>();

            foreach (var _compilation in compilationLibrary)
            {
                try
                {
                    assemblyList.Add(AssemblyLoadContext.Default.LoadFromAssemblyName(new AssemblyName(_compilation.Name)));
                }
                catch (Exception ex)
                {
                    Console.WriteLine(_compilation.Name + ex.Message);
                }
            }

            builder.RegisterAssemblyTypes(assemblyList.ToArray())
                .Where(type => baseType.IsAssignableFrom(type) && !type.IsAbstract)
                .AsSelf().AsImplementedInterfaces()
                .InstancePerLifetimeScope();
        }


    }
}